package cn.muqingfeng.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.net.http.AndroidHttpClient;
import android.text.TextUtils;

import cn.muqingfeng.api.RequestHelper;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class UploadFileUtil {

	public static <T> T uploadFile(HttpPost request, String url, Map<String, String> data, Map<String, File> files, Class<T> clazz) throws ParseException,
			IOException, HttpResponseException {
		request = request == null ? new HttpPost() : request;
		request.setURI(URI.create(url));
		Charset charset = Charset.forName(HTTP.UTF_8);
		MultipartEntity entity = new MultipartEntity();
		// 添加传回参数
		if (data != null && !data.isEmpty()) {
			for (Map.Entry<String, String> entry : data.entrySet()) {
				entity.addPart(entry.getKey(), new StringBody(entry.getValue(), charset));
			}
		}

		// 添加文件
		if (files != null && !files.isEmpty()) {
			for (Map.Entry<String, File> entry : files.entrySet()) {
				entity.addPart(entry.getKey(), new FileBody(entry.getValue()));
			}
		}
		try {
			request.setEntity(entity);
			HttpResponse response = AndroidHttpClient.newInstance(RequestHelper.UA) .execute(request);
			return processResponse(response, clazz);
		} catch (Exception e) {
			throw new IOException(e.getMessage());
		}
	}

	/**
	 * 处理响应结果
	 * 
	 * @param response
	 * @param clazz
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	private static <T> T processResponse(HttpResponse response, Class<T> clazz) throws ParseException, IOException, HttpResponseException {
		int statusCode = response.getStatusLine().getStatusCode();

		if (statusCode == HttpStatus.SC_OK) {
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity);

			entity.consumeContent(); // 释放或销毁内容

			if (TextUtils.isEmpty(result)) {
				return null;
			}
			// 将返回的文本结果进行json解析
			GsonBuilder gsonb = new GsonBuilder();
			gsonb.serializeNulls();
			Gson gson = gsonb.create();
			if (clazz.equals(Map.class)) {
				Type mapType = new TypeToken<Map<String, String>>() {
				}.getType();
				return gson.fromJson(result, mapType);
			} else if (clazz.equals(String.class)) {
				return (T) result;
			} else {
				return gson.fromJson(result, clazz);
			}
		} else {
			return null;
		}
	}
}
